package com.app.controller;

import com.app.common.EducationTool;
import com.app.common.IndustryTool;
import com.app.mapper.NewsMapper;
import com.app.mapper.VideoTrainMapper;
import com.app.model.*;
import com.app.service.*;
import com.app.util.CommonHelp;
import com.app.util.Result;
import com.app.util.TokenUtils;
import com.app.vo.NewsTypeCountVo;
import com.app.vo.NewsVo;
import com.app.vo.returnVo;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;


@RestController
@Controller
@RequestMapping("/news")
public class NewsController {

    @Autowired
    JdbcTemplate jdbcTemplate;
    @Autowired
    UserService userService;
    @Autowired
    UserPolicyInfoService userPolicyInfoService;

    @Autowired
    NewsService newsService;
    @Autowired
    AdminUserService adminUserService;
    @Autowired
    NewsMapper newsMapper;

    @Autowired
    VideoTrainMapper videoTrainMapper;
    @Autowired
    ConfigService configService;

    //查询数据库的所有信息
    //没有实体类，数据库里的东西，怎么获取？ Map

    //查
    @GetMapping("/newsList")
    public Result<Object> userList(HttpServletRequest request,Integer zcType) {

        String newType = request.getParameter("type");
        Integer page = Integer.valueOf(request.getParameter("page"));
        Integer limit = Integer.valueOf(request.getParameter("limit"));
        String keyword = request.getParameter("keyword");
        String sql;
        String sql2 = null;
        int type = Integer.parseInt(newType);
        String token = request.getHeader("token");
        UserPolicyInfoModel model = null;
        if (token != null) {
            String mobile = TokenUtils.verify(token);
            UserModel user = userService.getUserByMobile(mobile);

            if (user != null) {
                model = userPolicyInfoService.getModelByUserId(user.getId());
            }
        }


        if (zcType!=null && zcType!=1&&type >= 5 && model != null) {
            String seat = null;
            String identity = null;
            String education = null;
            String workingCondition = null;
            if (model.getSeat() == 1) {
                seat = "境内";
            } else if (model.getSeat() == 2) {
                seat = "境外";
            }
            if (model.getIdentity() == 1) {
                identity = "应届";
            } else if (model.getIdentity() == 2) {
                identity = "非应届";
            }
            for (int i = 0; i < EducationTool.EDUCATION_VO_LIST.size(); i++) {
                if (EducationTool.EDUCATION_VO_LIST.get(i).getId() == model.getEducation()) {
                    education = EducationTool.EDUCATION_VO_LIST.get(i).getData();
                }
            }
            if (model.getWorkingCondition() == 1) {
                workingCondition = "就业";
            } else if (model.getWorkingCondition() == 2) {
                workingCondition = "创业";
            }
            StringBuffer buff = new StringBuffer();
            StringBuffer buff2 = new StringBuffer();
            buff.append("select * from tb_news where type = '").append(newType).append("'");
            buff2.append("select COUNT(*) from tb_news where type = '").append(newType).append("'");
            buff.append(" AND (title like '%").append(seat).append("%'");
            buff2.append(" AND (title like '%").append(seat).append("%'");
            buff.append(" OR title like '%").append(identity).append("%'");
            buff2.append(" OR title like '%").append(identity).append("%'");
            buff.append(" OR title like '%").append(model.getSchoolName()).append("%'");
            buff2.append(" OR title like '%").append(model.getSchoolName()).append("%'");
            buff.append(" OR title like '%").append(model.getMajor()).append("%'");
            buff2.append(" OR title like '%").append(model.getMajor()).append("%'");
            buff.append(" OR title like '%").append(education).append("%'");
            buff2.append(" OR title like '%").append(education).append("%'");
            buff.append(" OR title like '%").append(workingCondition).append("%'");
            buff2.append(" OR title like '%").append(workingCondition).append("%'");
            buff.append(" OR content like '%").append(seat).append("%'");
            buff2.append(" OR content like '%").append(seat).append("%'");
            buff.append(" OR content like '%").append(identity).append("%'");
            buff2.append(" OR content like '%").append(identity).append("%'");
            buff.append(" OR content like '%").append(model.getSchoolName()).append("%'");
            buff2.append(" OR content like '%").append(model.getSchoolName()).append("%'");
            buff.append(" OR content like '%").append(model.getMajor()).append("%'");
            buff2.append(" OR content like '%").append(model.getMajor()).append("%'");
            buff.append(" OR content like '%").append(education).append("%'");
            buff2.append(" OR content like '%").append(education).append("%'");
            buff.append(" OR content like '%").append(workingCondition).append("%'");
            buff2.append(" OR content like '%").append(workingCondition).append("%'");
            if (model.getQualificationsState() == 1) {
                buff.append(" OR title like '%职业证书%'");
                buff.append(" OR content like '%职业证书%'");
                buff2.append(" OR title like '%职业证书%'");
                buff2.append(" OR content like '%职业证书%'");
            }
            if (model.getTitleState() == 1) {
                buff.append(" OR title like '%技术职称%'");
                buff.append(" OR content like '%技术职称%'");
                buff2.append(" OR title like '%技术职称%'");
                buff2.append(" OR content like '%技术职称%'");
            }
            if (model.getIndustry() > 0) {
                buff.append(" OR title like '%").append(IndustryTool.myMap.get(model.getIndustry())).append("%'");
                buff.append(" OR content like '%").append(IndustryTool.myMap.get(model.getIndustry())).append("%'");
                buff2.append(" OR title like '%").append(IndustryTool.myMap.get(model.getIndustry())).append("%'");
                buff2.append(" OR content like '%").append(IndustryTool.myMap.get(model.getIndustry())).append("%'");
            }
            if (keyword != null) {
                buff.append(" OR title like '%").append(keyword).append("%'");
                buff.append(" OR content like '%").append(keyword).append("%'");
                buff2.append(" OR title like '%").append(keyword).append("%'");
                buff2.append(" OR content like '%").append(keyword).append("%'");
            }
            buff.append(" ) ");
            buff2.append(" ) ");

            buff.append(" ORDER BY id DESC ");
            buff.append(" LIMIT  " + (page - 1) * limit + ", " + limit + " ");
            sql = buff.toString();
            sql2 = buff2.toString();
        } else if (type > 0) {
            sql = "select * from tb_news where type = '" + newType + "' ";
            sql2 = "select COUNT(*) from tb_news where type = '" + newType + "' ";
            if (keyword != null) {
                sql += "AND(title like '%" + keyword + "%' OR content like '%" + keyword + "%')";
                sql2 += "AND(title like '%" + keyword + "%' OR content like '%" + keyword + "%')";

            }
            sql += "ORDER BY id DESC " + " LIMIT  " + (page - 1) * limit + ", " + limit + " ";

        } else {
            sql = "select * from tb_news WHERE 1=1  ";
            sql2 = "select COUNT(*) from tb_news WHERE 1=1  ";
            if (keyword != null) {
                sql += " AND (title like '%" + keyword + "%' OR content like '%" + keyword + "%')";
                sql2 += " AND (title like '%" + keyword + "%' OR content like '%" + keyword + "%')";
            }
            sql += "ORDER BY id DESC" + " LIMIT  " + (page - 1) * limit + ", " + limit + "";
        }
        List<Map<String, Object>> list_maps = jdbcTemplate.queryForList(sql);

        Object count = jdbcTemplate.queryForObject(sql2,Integer.class);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        for (int i = 0; i < list_maps.size(); i++) {
            String bir = sdf.format(list_maps.get(i).get("crt_time"));
            list_maps.get(i).put("crt_time", bir);
        }
        NewsVo vo = new NewsVo();
        vo.setCount(Integer.valueOf(String.valueOf(count)));
        vo.setList(list_maps);
        return Result.success(vo);
    }
    @GetMapping("/selectTypeCount")
    public Result<Object> selectTypeCount() {

        List<NewsTypeCountVo> countVos = new ArrayList<>();
        List<NewsModel> newsModels = newsMapper.selectList(null);
        for (int i = 1; i <= 8; i++) {
            int finalI = i;
            List<NewsModel> collect = newsModels.stream().filter(NewsModel -> NewsModel.getType() == finalI).collect(Collectors.toList());
            NewsTypeCountVo vo = new NewsTypeCountVo();
            vo.setCount(collect.size());
            if (i == 1) {
                vo.setType(1);
                vo.setTypeText("政策法规");
            }
            if (i == 2) {
                vo.setType(2);
                vo.setTypeText("通知公告");
            }
            if (i == 3) {
                vo.setType(3);
                vo.setTypeText("职场资讯");
            }
            if (i == 4) {
                vo.setType(4);
                vo.setTypeText("补贴申请");
            }
            if (i == 5) {
                vo.setType(5);
                vo.setTypeText("经济补贴类");
            }
            if (i == 6) {
                vo.setType(6);
                vo.setTypeText("住房保障类");
            }
            if (i == 7) {
                vo.setType(7);
                vo.setTypeText("服务保障类");
            }
            if (i == 8) {
                vo.setType(8);
                vo.setTypeText("其他类");
            }
            countVos.add(vo);
        }
        return Result.success(countVos);
    }
    @GetMapping("/getNewsListByKeyWord")
    public Result<Object> getNewsListBy(HttpServletRequest request) {
        String keyword = request.getParameter("keyword");
        String token = request.getHeader("token");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String mobile = TokenUtils.verify(token);
        UserModel user = userService.getUserByMobile(mobile);

        if (user == null) {
            return Result.error(405, "用户不存在");
        }
        String sql;
        StringBuffer buff = new StringBuffer();
        buff.append("select * from tb_news where 1=1");
        buff.append(" AND (title like '%").append(keyword).append("%'");
        buff.append(" OR content like '%").append(keyword).append("%'");
        buff.append(" ) ");
        sql = buff.toString();
        List<Map<String, Object>> list_maps = jdbcTemplate.queryForList(sql);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        for (int i = 0; i < list_maps.size(); i++) {
            String bir = sdf.format(list_maps.get(i).get("crt_time"));
            list_maps.get(i).put("crt_time", bir);
        }
        return Result.success(list_maps);
    }

    @GetMapping("/getMatchingCount")
    public Result<Object> getMatchingCount(HttpServletRequest request) {

        String newType = request.getParameter("type");
        String keyword = request.getParameter("keyword");
        int type = Integer.parseInt(newType);
        int count = 0;
        String token = request.getHeader("token");
        if (token == null) {
            return Result.error(405, "token不存在");

        }
        String mobile = TokenUtils.verify(token);
        UserModel user = userService.getUserByMobile(mobile);

        if (user == null) {
            return Result.error(405, "用户不存在");
        }
        String sql;
        UserPolicyInfoModel model = userPolicyInfoService.getModelByUserId(user.getId());
        String seat = null;
        String identity = null;
        String education = null;
        String workingCondition = null;
        if (type >= 5 && model != null) {

            if (model.getSeat() == 1) {
                seat = "境内";
            } else if (model.getSeat() == 2) {
                seat = "境外";
            }
            if (model.getIdentity() == 1) {
                identity = "应届";
            } else if (model.getIdentity() == 2) {
                identity = "非应届";
            }
            for (int i = 0; i < EducationTool.EDUCATION_VO_LIST.size(); i++) {
                if (EducationTool.EDUCATION_VO_LIST.get(i).getId() == model.getEducation()) {
                    education = EducationTool.EDUCATION_VO_LIST.get(i).getData();
                }
            }
            if (model.getWorkingCondition() == 1) {
                workingCondition = "就业";
            } else if (model.getWorkingCondition() == 2) {
                workingCondition = "创业";
            }
            StringBuffer buff = new StringBuffer();
            buff.append("select COUNT(*) from tb_news where type = '").append(newType).append("'");
            buff.append(" AND (title like '%").append(seat).append("%'");
            buff.append(" OR title like '%").append(identity).append("%'");
            buff.append(" OR title like '%").append(model.getSchoolName()).append("%'");
            buff.append(" OR title like '%").append(model.getMajor()).append("%'");
            buff.append(" OR title like '%").append(education).append("%'");
            buff.append(" OR title like '%").append(workingCondition).append("%'");
            buff.append(" OR content like '%").append(seat).append("%'");
            buff.append(" OR content like '%").append(identity).append("%'");
            buff.append(" OR content like '%").append(model.getSchoolName()).append("%'");
            buff.append(" OR content like '%").append(model.getMajor()).append("%'");
            buff.append(" OR content like '%").append(education).append("%'");
            buff.append(" OR content like '%").append(workingCondition).append("%'");
            if (model.getQualificationsState() == 1) {
                buff.append(" OR title like '%职业证书%'");
                buff.append(" OR content like '%职业证书%'");
            }
            if (model.getTitleState() == 1) {
                buff.append(" OR title like '%技术职称%'");
                buff.append(" OR content like '%技术职称%'");
            }
            if (model.getIndustry() > 0) {
                buff.append(" OR title like '%").append(IndustryTool.myMap.get(model.getIndustry())).append("%'");
                buff.append(" OR content like '%").append(IndustryTool.myMap.get(model.getIndustry())).append("%'");
            }
            if (keyword != null) {
                buff.append(" OR title like '%").append(keyword).append("%'");
                buff.append(" OR content like '%").append(keyword).append("%'");
            }
            buff.append(" ) ");
            sql = buff.toString();
            count = jdbcTemplate.queryForObject(sql, Integer.class);

        }

        return Result.success(count);
    }

    @GetMapping("/getNewById")
    public Result<Object> getNewById(HttpServletRequest request) {

        String id = request.getParameter("id");
        String sql = "select * from tb_news where id = '" + id + "'";
        List<Map<String, Object>> list_maps = jdbcTemplate.queryForList(sql);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        for (int i = 0; i < list_maps.size(); i++) {
            String bir = sdf.format(list_maps.get(i).get("crt_time"));
            list_maps.get(i).put("crt_time", bir);
        }

        return Result.success(list_maps);
    }

    @GetMapping("/policyList")
    public Result<Object> policyList(HttpServletRequest request) {
        String policyType = request.getParameter("type");
        JSONObject json = new JSONObject();
        String sql = "select id,title,content,crt_time,ima_url from  tb_news  where type = '" + policyType + "' ORDER BY id DESC ";
        List<Map<String, Object>> list_maps = jdbcTemplate.queryForList(sql);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        for (int i = 0; i < list_maps.size(); i++) {
            String bir = sdf.format(list_maps.get(i).get("crt_time"));
            list_maps.get(i).put("crt_time", bir);
        }
        System.out.println(list_maps);
        json.put("code", "1");
        json.put("msg", "成功");
        json.put("data", list_maps);
        return Result.success(list_maps);
    }

    @PostMapping("/insertAndUpdateNews")
    public String insertNews(HttpServletRequest request,
                             @RequestBody NewsModel model){
        JSONObject json = new JSONObject();
        if(model.getId()==0){
            model.setCrtTime(String.valueOf(CommonHelp.getNowTimestamp()));
            newsMapper.insert(model);
        }else {
            newsMapper.update(model);
        }
        json.put("code", 200);
        json.put("msg", "成功");
        return json.toString();
    }
    @GetMapping("/getNewsList")
    public String getNewsList(HttpServletRequest request,
                              @RequestParam(required = false) String keyWord,
                              @RequestParam(required = false) String startTime,
                              @RequestParam(required = false) String endTime,
                              int page,
                              int limit,
                              Integer typeId){
        JSONObject json = new JSONObject();
        String token = request.getHeader("token");
        String adminId = TokenUtils.verify(token);

        NewsModel model = new NewsModel();
        model.setPage((page - 1) * limit);
        model.setLimit(limit);
        model.setKeyWord(keyWord);
        model.setStartTime(startTime);
        model.setEndTime(endTime);
        if(typeId!=null)
        {
            model.setType(typeId);
        }
        List<NewsModel> modelList = newsMapper.getNewsList(model);//查列表
        for (int i = 0; i < modelList.size(); i++) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            Timestamp data = Timestamp.valueOf(modelList.get(i).getCrtTime());
            String currentSimpleDateFormat = simpleDateFormat.format(data);
            modelList.get(i).setCrtTime(currentSimpleDateFormat);
            ConfigModel configModel = configService.getModelById(modelList.get(i).getType());
            if(configModel!=null)
            {
                modelList.get(i).setTypeText(configModel.getName());
            }
        }
//      int count = newsMapper.getModelCount(model);//查数量
        int count = newsMapper.countAll(model);//查数量
        JSONObject job = new JSONObject();
        job.put("list",modelList);
        job.put("count",count);
        json.put("data",job);
        json.put("code",200);
        json.put("message","成功");
        return json.toString();
    }

    @GetMapping("/newsTypeName")
    public String getNewsName(){
        JSONObject json = new JSONObject();
        List<ConfigModel> configModelList = findChildren(configService.getGroupListByType(6,null),0);
        json.put("data",configModelList);
        json.put("code",200);
        json.put("message","成功");
        return json.toString();
    }

    private List<ConfigModel> findChildren(List<ConfigModel> modelList, Integer pid){//递归方法
        List<ConfigModel> personModelList= new ArrayList<>();
        for (int i = 0; i < modelList.size(); i++) {
            if(Objects.equals(modelList.get(i).getFatherId(), pid))
            {
                ConfigModel model = modelList.get(i);
                List<ConfigModel> modelList1 = findChildren(modelList,model.getId());
                for (int j = 0; j < modelList1.size(); j++) {
                    if(modelList1!=null&&modelList1.size()>0)
                    {
                        model.setChild(modelList1);
                    }
                }
                personModelList.add(model);
            }
        }
        return personModelList;
    }

    @GetMapping("/getNewsById")
    public String getNewsById(HttpServletRequest request,
                              @RequestParam("id") int id){
        JSONObject json = new JSONObject();

        NewsModel model = newsMapper.getNewsById(id);
        if(model==null){
            json.put("code",500);
            json.put("message","空值或者传参错误");
        }
        JSONObject obj = new JSONObject(model);
        json.put("data",obj);
        json.put("code",200);
        json.put("message","成功");
        return json.toString();
    }

    /**
     * 删除新闻
     */
    @PostMapping("/deleteNews")
    @ResponseBody
    public Result<Object> deleteNews(HttpServletRequest request,Integer id) {
        String token = request.getHeader("token");
        String userId = TokenUtils.nothingness(token);
        if (userId == null) {
            return Result.error(405,"token不存在");
        }
        AdminUserModel user = adminUserService.getUserById(Integer.parseInt(userId));
        if(user==null)
        {
            return Result.error(405,"用户不存在");
        }
        newsService.delete(id);
        return Result.success("操作成功");
    }

}



